package com.blog4j.user.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog4j.common.constants.CommonConstant;
import com.blog4j.common.enums.ApproveEnum;
import com.blog4j.common.enums.ErrorEnum;
import com.blog4j.common.enums.RoleEnum;
import com.blog4j.common.exception.Blog4jException;
import com.blog4j.user.entity.ApplyOrganizationEntity;
import com.blog4j.user.entity.OrganizationEntity;
import com.blog4j.user.mapper.ApplyOrganizationMapper;
import com.blog4j.user.mapper.OrganizationMapper;
import com.blog4j.user.service.ApplyOrganizationService;
import com.blog4j.user.utils.UserUtil;
import com.blog4j.user.vo.req.ApplyOrganizationListReqVo;
import com.blog4j.user.vo.req.DeleteApplyCreateOrganizationReqVo;
import com.blog4j.user.vo.resp.ApplyOrganizationRespVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 98k灬
 * @version v1.0.0
 * @Description : 功能描述
 * @Create on : 2024/8/12 19:49
 **/
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class ApplyOrganizationServiceImpl extends ServiceImpl<ApplyOrganizationMapper, ApplyOrganizationEntity>
        implements ApplyOrganizationService {
    private final UserUtil userUtil;
    private final OrganizationMapper organizationMapper;
    /**
     * 获取申请创建组织信息的列表
     *
     * @param reqVo 请求
     * @return 申请创建组织信息的列表
     */
    @Override
    public PageInfo<ApplyOrganizationRespVo> getApplyOrganizationList(ApplyOrganizationListReqVo reqVo) {
        String organizationName = reqVo.getOrganizationName();
        Integer approveStatus = reqVo.getApproveStatus();
        Integer pageSize = reqVo.getPageSize();
        if (pageSize > CommonConstant.MAX_PAGE_SIZE) {
            pageSize = CommonConstant.MAX_PAGE_SIZE;
        }
        Integer pageNo = reqVo.getPageNo();
        String userName = reqVo.getUserName();

        PageHelper.startPage(pageNo, pageSize);
        List<ApplyOrganizationRespVo> list =
                this.baseMapper.getApplyOrganizationList(organizationName, approveStatus, userName);
        if (CollectionUtil.isEmpty(list)) {
            return new PageInfo<>(new ArrayList<>());
        }

        for (ApplyOrganizationRespVo resp : list) {
            resp.setApproveUserId(userUtil.getSuperAdminUserId())
                    .setApproveUserName(userUtil.getSuperAdminUserName());
        }
        return new PageInfo<>(list);
    }

    /**
     * 删除用户申请创建组织记录
     *
     * @param reqVo 请求
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteApplyCreateOrganization(DeleteApplyCreateOrganizationReqVo reqVo) {
        List<Integer> ids = reqVo.getIds();
        List<ApplyOrganizationEntity> list = this.baseMapper.selectBatchIds(ids);
        if (CollectionUtil.isEmpty(list)) {
            return;
        }
        Set<String> organizationIdSet = list.stream()
                .map(ApplyOrganizationEntity::getOrganizationId).collect(Collectors.toSet());
        List<OrganizationEntity> organizationList = organizationMapper.selectBatchIds(organizationIdSet);
        if (CollectionUtil.isEmpty(organizationList)) {
            throw new Blog4jException(ErrorEnum.SYSTEM_ERROR);
        }
        List<OrganizationEntity> collect = organizationList.stream().filter(item -> Objects.equals(item.getApproveStatus(), ApproveEnum.WAIT_APPROVE.getCode()))
                .collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(collect)) {
            throw new Blog4jException(ErrorEnum.INVALID_PARAMETER_ERROR);
        }

        List<String> roleList = StpUtil.getRoleList();
        String role = roleList.get(0);
        String userId = StpUtil.getLoginIdAsString();
        if (StringUtils.equals(RoleEnum.ORGANIZATION_ADMIN.getDesc(), role)) {
            List<OrganizationEntity> collect1 = organizationList.stream()
                    .filter(item -> !StringUtils.equals(item.getOrganizationAdmin(), userId)).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(collect1)) {
                throw new Blog4jException(ErrorEnum.INVALID_PARAMETER_ERROR);
            }
        }
        this.baseMapper.deleteBatchIds(ids);
    }
}
